document.addEventListener('DOMContentLoaded', function() {
    const currentUser = localStorage.getItem('username'); // 假设登录时保存了用户名
    viewArticles(1, 5, currentUser); // 默认加载第1页，每页5条
});
/*<p>${record.content}</p>*/
function viewArticles(page, pageSize, currentUser) {
    fetch(`/blog/text/listText?page=${page}&pageSize=${pageSize}`)
        .then(response => response.json())
        .then(data => {
            const articlesDiv = document.getElementById('articles');
            if (data.code === 1) {
                const articles = data.data.records.map(record => {
                    const isCurrentUserArticle = record.username === currentUser;
                    return `
                    <div ${isCurrentUserArticle ? 'style="background-color: #e0ffe0;"' : ''}>
                        <h3><a href="article-detail.html?id=${record.id}">${record.title}</a></h3>
                        
                        <small>作者：${record.username} 分类：${record.type} 时间：${new Date(record.createTime).toLocaleString()}</small>
                        ${isCurrentUserArticle ? `
                            <button onclick="editArticle(${record.id}, '${record.title}', '${record.content}', '${record.type}')">编辑</button>
                            <button onclick="deleteArticle(${record.id})">删除</button>
                        ` : ''}
                    </div>
                `;
                }).join('');
                articlesDiv.innerHTML = articles;

                // 添加分页按钮
                const paginationDiv = document.getElementById('pagination');
                const totalPages = Math.ceil(data.data.total / pageSize);
                paginationDiv.innerHTML = createPaginationButtons(page, totalPages);
            } else {
                articlesDiv.innerHTML = `<p>加载失败：${data.msg}</p>`;
            }
        })
        .catch(error => {
            const articlesDiv = document.getElementById('articles');
            articlesDiv.innerHTML = `<p>请求失败：${error.message}</p>`;
        });
}

function createPaginationButtons(currentPage, totalPages) {
    let buttons = '';

    for (let i = 1; i <= totalPages; i++) {
        buttons += `<button ${i === currentPage ? 'class="active"' : ''} onclick="changePage(${i})">${i}</button>`;
    }

    return buttons;
}

function changePage(page) {
    const currentUser = localStorage.getItem('username'); // 获取当前用户名
    viewArticles(page, 5, currentUser); // 每页10条
}

function editArticle(id, title, content, type) {
    const newTitle = prompt('修改标题', title);
    const newContent = prompt('修改内容', content);
    const newType = prompt('修改分类', type);

    if (newTitle && newContent && newType) {
        fetch(`/blog/user/update`, {  // 假设更新文章的接口为 `/blog/user/update`
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ id, title: newTitle, content: newContent, type: newType })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    alert('修改成功');
                    viewArticles(1, 5, localStorage.getItem('username')); // 重新加载文章列表
                } else {
                    alert('修改失败：' + data.msg);
                }
            })
            .catch(error => {
                alert('请求失败：' + error.message);
            });
    }
}

function deleteArticle(id) {
    if (confirm('确定要删除这篇文章吗？')) {
        fetch(`/blog/user/delete/${id}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    alert('删除完成');
                    viewArticles(1, 5, localStorage.getItem('username')); // 重新加载文章列表
                } else {
                    alert('删除失败：' + data.msg);
                }
            })
            .catch(error => {
                alert('请求失败：' + error.message);
            });
    }
}
